﻿

#include"file.h"

extern pTec Thead;//定义指向教师的指针
extern pStu Shead;//定义指向学生的指针


//读学生文件
pStu readSFileToMemory()
{
	pStu Shead=(pStu)malloc(sizeof(Student));
	pStu p=Shead;
	//1.打开文件
	FILE *fp=fopen(SFILENAME,"r");
		if(fp==NULL)
		{
			perror("fopen failed");
			return NULL;
		}
	//2.写操作
		int length=0;
		fread(&length,sizeof(int),1,fp);
		int i=1;
	
		for(;i<=length;i++)
		{
			pStu q=(pStu)malloc(sizeof(Student));
			fread(&q->data,sizeof(Student),1,fp);
			p->next=q;
			q->next=NULL;
			p=p->next;
		}
	//3.关闭文件
			fclose(fp);
	return Shead;
	
}
//保存学生数据
void saveSDataToFile(pStu Shead)
{
	//1.打开文件
	FILE *fp=fopen(SFILENAME,"w");
		if(fp==NULL)
		{
			perror("fopen failed");
			return ;
		}
	int length = getStuLength(Shead);
	fwrite(&length,sizeof(int),1,fp);
	//2.写操作
		pStu temp=Shead->next;
		for(;temp!=NULL;temp=temp->next)
		{
			fwrite(&temp->data,sizeof(Student),1,fp);		
		}
	//3.关闭文件
			fclose(fp);
}


//读教师文件
pTec readTFileToMemory()
{
	pTec Thead=(pTec)malloc(sizeof(Teacher));
	pTec p=Thead;
	//1.打开文件
	FILE *fp=fopen(TFILENAME,"r");
		if(fp==NULL)
		{
			perror("fopen failed");
			return NULL;
		}
	//2.写操作
		int length=0;
		fread(&length,sizeof(int),1,fp);
		int i=1;
	
		for(;i<=length;i++)
		{
			pTec q=(pTec)malloc(sizeof(Teacher));
			fread(&q->data,sizeof(Teacher),1,fp);
			p->next=q;
			q->next=NULL;
			p=p->next;
		}
	//3.关闭文件
			fclose(fp);
	return Thead;
	
}
//保存教师数据
void saveTDataToFile(pTec Thead)
{
	//1.打开文件
	FILE *fp=fopen(TFILENAME,"w");
		if(fp==NULL)
		{
			perror("fopen failed");
			return ;
		}
	int length = getTecLength(Thead);
	fwrite(&length,sizeof(int),1,fp);
	//2.写操作
		pTec temp=Thead->next;
		for(;temp!=NULL;temp=temp->next)
		{
			fwrite(&temp->data,sizeof(Teacher),1,fp);		
		}
	//3.关闭文件
			fclose(fp);
}

